package struts.listener;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import struts.bean.StrutsConfig;


public class StrutsLinstener implements ServletContextListener {
	private static final String STRUTS_CONFIG = "/WEB-INF/classes/struts.xml";
	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("正在启动服务器！");
		ServletContext context = arg0.getServletContext();
		String strutsConfig = context.getInitParameter("struts-config");
		if(null == strutsConfig || "".equals(strutsConfig)){
			strutsConfig = STRUTS_CONFIG;
		}
		String tomcatPath = context.getRealPath("\\");
		String strutsXMLPath = tomcatPath+strutsConfig;
		// 读取配置文件获取struts配置文件的map对象
		Document document = null;
		Map<String,StrutsConfig> map = new HashMap<String, StrutsConfig>();
		try{
			// 创建SAxReader对象
			SAXReader saxReader = new SAXReader();
			// 读取配置文件
			document = saxReader.read(new File(strutsXMLPath));
			// 获取根节点
			Element root = document.getRootElement();
			// 获取package节点
			Element packageEle = root.element("package");
			// 获取package节点下的属性
			String packageName = packageEle.attribute("namespace").getValue()+"/";
			//System.out.println(attr.getName()+"="+attr.getValue());
			// 获取action节点列表
			@SuppressWarnings("unchecked")
			List<Element> actionList = packageEle.elements();
			for(Element element : actionList){
				StrutsConfig config = new StrutsConfig();
				// 获取action下的属性，并将属性放入bean中
				Attribute attrName = element.attribute("name");
				Attribute attrClass = element.attribute("class");
				Attribute attrMethod = element.attribute("method");
				config.setActionName(attrName.getValue());
				config.setActionClass(attrClass.getValue());
				config.setMethod(attrMethod.getValue());
				List<Element> resultList = element.elements();
				Map<String, String> resultMap = new HashMap<String, String>();
				for(Element resultEle : resultList){
					Attribute attrResultName = resultEle.attribute("name");
					String resultUrl = resultEle.getTextTrim();
					resultMap.put(attrResultName.getValue(), resultUrl);
				}
				config.setResultMap(resultMap);
				// 组装map, map的键值为namespace+actionName, value值为组装的strtusXmlBean
				map.put(packageName+attrName.getValue(), config);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		context.setAttribute("actionMap", map);
		System.out.println(map);
	}
	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("正在关闭服务器！");
	}
}
